{% extends "base.html" %}

{% set current_menu = 'project' %}
{% set current_page = 'project_list' %}

{% block title %}项目列表 - 项目管理系统{% endblock %}

{% block page_title %}{% endblock %}
{% block page_subtitle %}{% endblock %}

{% block content %}
<div class="container mx-auto">
    <!-- 面包屑导航 -->
    <nav class="text-sm breadcrumbs mb-6">
        <ol class="flex items-center space-x-2">
            <li><a href="{{ url_for('main.home') }}" class="text-gray-500 hover:text-gray-700">首页</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li><a href="{{ url_for('project.list_projects') }}" class="text-gray-500 hover:text-gray-700">项目管理</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li class="text-gray-700">项目列表</li>
        </ol>
    </nav>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-500">
                    <i class="fas fa-project-diagram"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">项目总数</p>
                    <p class="text-2xl font-semibold">{{ stats.total }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-500">
                    <i class="fas fa-spinner"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">进行中</p>
                    <p class="text-2xl font-semibold">{{ stats.in_progress }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-yellow-100 text-yellow-500">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">已完成</p>
                    <p class="text-2xl font-semibold">{{ stats.completed }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-red-100 text-red-500">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">已延期</p>
                    <p class="text-2xl font-semibold">{{ stats.overdue }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作区域 -->
    <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-4 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                <div class="flex items-center space-x-2 mb-4 md:mb-0">
                    <button id="project-initiation-btn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                        <i class="fas fa-plus-circle mr-2"></i>项目立项
                    </button>
                    <button class="px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition">
                        <i class="fas fa-file-export mr-2"></i>批量导出
                    </button>
                </div>
                <div class="flex items-center space-x-2">
                    <div class="relative">
                        <input type="text" id="search" placeholder="搜索项目名称、编号..." 
                               class="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                               value="{{ search }}">
                        <div class="absolute left-3 top-2.5 text-gray-400">
                            <i class="fas fa-search"></i>
                        </div>
                    </div>
                    <button id="search-btn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                        搜索
                    </button>
                </div>
            </div>
        </div>

        <!-- 筛选区域 -->
        <div class="p-4 border-b border-gray-200">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">项目状态</label>
                    <select id="status-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部状态</option>
                        <option value="未开始">未开始</option>
                        <option value="进行中">进行中</option>
                        <option value="已完成">已完成</option>
                        <option value="已延期">已延期</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">项目类型</label>
                    <select id="type-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部类型</option>
                        <option value="产品研发">产品研发</option>
                        <option value="技术改进">技术改进</option>
                        <option value="系统升级">系统升级</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">负责人</label>
                    <select id="manager-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部负责人</option>
                        {% for manager in managers %}
                        <option value="{{ manager.id }}" {% if manager_filter == manager.id|string %}selected{% endif %}>{{ manager.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">销售负责人</label>
                    <select id="sales-manager-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部销售负责人</option>
                        {% for sales_manager in sales_managers %}
                        <option value="{{ sales_manager.id }}" {% if sales_manager_filter == sales_manager.id|string %}selected{% endif %}>{{ sales_manager.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">项目来源</label>
                    <select id="source-filter" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="">全部来源</option>
                        {% for source in sources %}
                        <option value="{{ source }}" {% if source_filter == source %}selected{% endif %}>{{ source }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="mt-4 flex justify-end">
                <button id="filter-btn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                    查询
                </button>
                <button id="reset-btn" class="ml-2 px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition">
                    重置
                </button>
            </div>
        </div>

        <!-- 项目列表表格 -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" id="select-all" class="rounded border-gray-300 text-primary focus:ring-primary">
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            项目名称
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            项目编号
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            项目类型
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            项目来源
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            关联客户
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            项目规模
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            负责人
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            销售负责人
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            状态
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            进度
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% if projects.items %}
                        {% for project in projects.items %}
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="checkbox" class="project-checkbox rounded border-gray-300 text-primary focus:ring-primary" value="{{ project.id }}">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div>
                                        <div class="text-sm font-medium text-gray-900">
                                            <a href="{{ url_for('project.view_project', project_id=project.id) }}" class="hover:text-primary">{{ project.name }}</a>
                                        </div>
                                        <div class="text-sm text-gray-500">
                                            {{ project.start_date.strftime('%Y-%m-%d') if project.start_date else '未设置' }} - {{ project.end_date.strftime('%Y-%m-%d') if project.end_date else '未设置' }}
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ project.project_number or '无' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ project.project_type or '产品研发' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ project.source or '内部创建' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {% if project.customer %}
                                        <a href="{{ url_for('customer.customer_detail', customer_id=project.customer.id) }}" class="text-primary hover:text-blue-600">
                                            {{ project.customer.name }}
                                        </a>
                                    {% else %}
                                        <span class="text-gray-400">未关联</span>
                                    {% endif %}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ project.scale or '中型' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ project.manager.name if project.manager else '未分配' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ project.sales_manager.name if project.sales_manager else '未分配' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                        {% if project.status == '未开始' %}bg-gray-100 text-gray-800
                                        {% elif project.status == '进行中' %}bg-blue-100 text-blue-800
                                        {% elif project.status == '已完成' %}bg-green-100 text-green-800
                                        {% else %}bg-red-100 text-red-800{% endif %}">
                                        {{ project.status }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="w-full bg-gray-200 rounded-full h-2.5">
                                        <div class="h-2.5 rounded-full progress-bar" 
                                             data-progress="{{ project.progress }}"
                                             style="width: {{ project.progress }}%; background-color: {% if project.progress >= 100 %}#10B981{% elif project.progress >= 50 %}#3B82F6{% else %}#F59E0B{% endif %};"></div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <div class="flex space-x-2">
                                        <a href="{{ url_for('project.view_project', project_id=project.id) }}" class="text-primary hover:text-blue-600">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="{{ url_for('project.edit_project', project_id=project.id) }}" class="text-indigo-600 hover:text-indigo-900">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <button class="delete-project text-red-600 hover:text-red-900" data-id="{{ project.id }}" data-name="{{ project.name }}">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        {% endfor %}
                    {% else %}
                        <tr>
                            <td colspan="12" class="px-6 py-4 text-center text-sm text-gray-500">
                                暂无项目数据
                            </td>
                        </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        显示 <span class="font-medium">{{ (projects.page - 1) * projects.per_page + 1 }}</span> 到 <span class="font-medium">{{ projects.page * projects.per_page if projects.page * projects.per_page < projects.total else projects.total }}</span> 条，
                        共 <span class="font-medium">{{ projects.total }}</span> 条记录
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                        {% if projects.has_prev %}
                        <a href="{{ url_for('project.list_projects', page=projects.page-1, **request.args) }}" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">上一页</span>
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        {% else %}
                        <span class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-gray-100 text-sm font-medium text-gray-400">
                            <span class="sr-only">上一页</span>
                            <i class="fas fa-chevron-left"></i>
                        </span>
                        {% endif %}
                        
                        {% for p in range(projects.page-2 if projects.page-2 > 0 else 1, projects.page+3 if projects.page+3 <= projects.pages+1 else projects.pages+1) %}
                        {% if p == projects.page %}
                        <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-primary text-sm font-medium text-white">
                            {{ p }}
                        </span>
                        {% else %}
                        <a href="{{ url_for('project.list_projects', page=p, **request.args) }}" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                            {{ p }}
                        </a>
                        {% endif %}
                        {% endfor %}
                        
                        {% if projects.has_next %}
                        <a href="{{ url_for('project.list_projects', page=projects.page+1, **request.args) }}" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">下一页</span>
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        {% else %}
                        <span class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-gray-100 text-sm font-medium text-gray-400">
                            <span class="sr-only">下一页</span>
                            <i class="fas fa-chevron-right"></i>
                        </span>
                        {% endif %}
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="delete-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3 text-center">
            <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                <i class="fas fa-exclamation-triangle text-red-600"></i>
            </div>
            <h3 class="text-lg leading-6 font-medium text-gray-900 mt-4">删除项目</h3>
            <div class="mt-2 px-7 py-3">
                <p class="text-sm text-gray-500">
                    确定要删除项目 "<span id="delete-project-name"></span>" 吗？此操作不可撤销。
                </p>
            </div>
            <div class="items-center px-4 py-3">
                <form id="delete-form" method="post">
                    <input type="hidden" id="delete-project-id" name="project_id">
                    <button type="button" id="cancel-delete" class="px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-24 mr-2 hover:bg-gray-400">
                        取消
                    </button>
                    <button type="submit" class="px-4 py-2 bg-red-600 text-white text-base font-medium rounded-md w-24 hover:bg-red-700">
                        删除
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 项目立项模态框 -->
<div id="project-initiation-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-10 mx-auto p-5 border w-4/5 max-w-4xl shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg leading-6 font-medium text-gray-900">项目立项</h3>
                <button id="close-initiation-modal" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="project-initiation-form" action="{{ url_for('project.project_initiation_ajax') }}" method="post">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="name">
                            项目名称 <span class="text-red-500">*</span>
                        </label>
                        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="name" name="name" type="text" required>
                    </div>
                    <div>
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="project_type">
                            项目类型
                        </label>
                        <select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="project_type" name="project_type">
                            <option value="产品研发">产品研发</option>
                            <option value="工程项目">工程项目</option>
                            <option value="咨询服务">咨询服务</option>
                            <option value="系统集成">系统集成</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="project_source">
                            项目来源
                        </label>
                        <select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="project_source" name="project_source">
                            <option value="公开招标">公开招标</option>
                            <option value="邀请招标">邀请招标</option>
                            <option value="竞争性谈判">竞争性谈判</option>
                            <option value="单一来源">单一来源</option>
                            <option value="内部立项">内部立项</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="manager_id">
                            项目经理
                        </label>
                        <select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="manager_id" name="manager_id">
                            {% for user in users %}
                            <option value="{{ user.id }}">{{ user.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div>
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="customer_id">
                            关联客户
                        </label>
                        <select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="customer_id" name="customer_id">
                            <option value="">无关联客户</option>
                            {% for customer in customers %}
                            <option value="{{ customer.id }}">{{ customer.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div>
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="budget">
                            项目预算（万元）
                        </label>
                        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="budget" name="budget" type="number" step="0.01" min="0">
                    </div>
                    <div>
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="start_date">
                            开始日期
                        </label>
                        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="start_date" name="start_date" type="date">
                    </div>
                    <div>
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="end_date">
                            结束日期
                        </label>
                        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="end_date" name="end_date" type="date">
                    </div>
                </div>
                <div class="mt-4">
                    <label class="block text-gray-700 text-sm font-bold mb-2" for="description">
                        项目描述
                    </label>
                    <textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="description" name="description" rows="4"></textarea>
                </div>
                <div class="mt-6 flex justify-end">
                    <button type="button" id="cancel-initiation" class="px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-24 mr-2 hover:bg-gray-400">
                        取消
                    </button>
                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white text-base font-medium rounded-md w-24 hover:bg-blue-700">
                        提交立项
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
{{ super() }}
<script>
    // 筛选面板折叠/展开功能
    document.addEventListener('DOMContentLoaded', function() {
        const filterToggle = document.querySelector('.filter-toggle');
        const filterPanel = document.querySelector('.filter-panel');
        
        if (filterToggle && filterPanel) {
            filterToggle.addEventListener('click', function() {
                filterPanel.classList.toggle('collapsed');
                const icon = filterToggle.querySelector('i');
                icon.classList.toggle('fa-chevron-down');
                icon.classList.toggle('fa-chevron-up');
            });
        }
        
        // 筛选功能
        const filterBtn = document.getElementById('filter-btn');
        const resetBtn = document.getElementById('reset-btn');
        
        // 获取所有筛选元素
        const statusFilter = document.getElementById('status-filter');
        const typeFilter = document.getElementById('type-filter');
        const managerFilter = document.getElementById('manager-filter');
        const salesManagerFilter = document.getElementById('sales-manager-filter');
        const sourceFilter = document.getElementById('source-filter');
        
        // 筛选按钮点击事件
        if (filterBtn) {
            filterBtn.addEventListener('click', function() {
                // 获取当前URL
                const url = new URL(window.location);
                
                // 设置筛选参数
                if (statusFilter.value) {
                    url.searchParams.set('status', statusFilter.value);
                } else {
                    url.searchParams.delete('status');
                }
                
                if (typeFilter.value) {
                    url.searchParams.set('type', typeFilter.value);
                } else {
                    url.searchParams.delete('type');
                }
                
                if (managerFilter.value) {
                    url.searchParams.set('manager', managerFilter.value);
                } else {
                    url.searchParams.delete('manager');
                }
                
                if (salesManagerFilter.value) {
                    url.searchParams.set('sales_manager', salesManagerFilter.value);
                } else {
                    url.searchParams.delete('sales_manager');
                }
                
                if (sourceFilter.value) {
                    url.searchParams.set('source', sourceFilter.value);
                } else {
                    url.searchParams.delete('source');
                }
                
                // 重置页码为第一页
                url.searchParams.delete('page');
                
                // 跳转到新的URL
                window.location.href = url.toString();
            });
        }
        
        // 重置按钮点击事件
        if (resetBtn) {
            resetBtn.addEventListener('click', function() {
                // 获取当前URL
                const url = new URL(window.location);
                
                // 删除所有筛选参数
                url.searchParams.delete('status');
                url.searchParams.delete('type');
                url.searchParams.delete('manager');
                url.searchParams.delete('sales_manager');
                url.searchParams.delete('source');
                url.searchParams.delete('page');
                
                // 重置筛选表单
                statusFilter.value = '';
                typeFilter.value = '';
                managerFilter.value = '';
                salesManagerFilter.value = '';
                sourceFilter.value = '';
                
                // 跳转到新的URL
                window.location.href = url.toString();
            });
        }
        
        // 删除项目确认功能
        const projectDeleteButtons = document.querySelectorAll('.delete-project');
        projectDeleteButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation(); // 阻止冒泡到行点击
                const projectId = this.getAttribute('data-id');
                const projectName = this.getAttribute('data-name');
                
                // 显示删除确认模态框
                document.getElementById('delete-project-id').value = projectId;
                document.getElementById('delete-project-name').textContent = projectName;
                document.getElementById('delete-modal').classList.remove('hidden');
                
                // 取消删除按钮事件
                document.getElementById('cancel-delete').addEventListener('click', function() {
                    document.getElementById('delete-modal').classList.add('hidden');
                });
            });
        });
        
        // 项目删除表单提交处理
        const deleteForm = document.getElementById('delete-form');
        if (deleteForm) {
            deleteForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const projectId = document.getElementById('delete-project-id').value;
                const projectName = document.getElementById('delete-project-name').textContent;
                
                // 使用AJAX提交删除请求
                fetch(`/projects/${projectId}/delete`, {
                    method: 'POST',
                    body: new FormData(this)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 显示成功消息
                        showNotification(data.message, 'success');
                        // 关闭删除确认模态框
                        document.getElementById('delete-modal').classList.add('hidden');
                        // 刷新页面以更新项目列表
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        // 显示错误消息
                        showNotification(data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showNotification('删除项目时发生错误', 'error');
                });
            });
        }
        
        // 检查是否需要显示空状态
        function checkEmptyState() {
            const projectRows = document.querySelectorAll('.project-table tbody tr:not(:has(.empty-state))');
            const emptyState = document.querySelector('.empty-state');
            const emptyRow = emptyState ? emptyState.closest('tr') : null;
            
            if (projectRows.length === 0 && emptyRow) {
                emptyRow.style.display = '';
            }
        }
        
        // 响应式处理
        function handleResize() {
            const screenWidth = window.innerWidth;
            const mobileNavToggle = document.querySelector('.mobile-nav-toggle');
            const sidebar = document.querySelector('.sidebar');
            
            // 在小屏幕上默认隐藏侧边栏
            if (screenWidth <= 768 && sidebar && !mobileNavToggle) {
                sidebar.classList.add('transform', '-translate-x-full');
            }
        }
        
        // 初始加载时执行一次
        handleResize();
        
        // 监听窗口大小变化
        window.addEventListener('resize', handleResize);
        
        // 添加通知提示功能 - 使用统一的flash消息系统
        function showNotification(message, type = 'success') {
            showFlashMessage(message, type);
        }
        
        // 统一的flash消息提示函数
        function showFlashMessage(message, type = 'success') {
            // 创建flash消息容器（如果不存在）
            let flashContainer = document.getElementById('flash-messages');
            if (!flashContainer) {
                flashContainer = document.createElement('div');
                flashContainer.id = 'flash-messages';
                flashContainer.className = 'fixed top-16 right-4 z-50 space-y-2';
                document.body.appendChild(flashContainer);
            }
            
            const flashMessage = document.createElement('div');
            flashMessage.className = `flash-message ${type === 'success' ? 'bg-green-500' : type === 'error' ? 'bg-red-500' : 'bg-blue-500'} text-white px-4 py-3 rounded-md shadow-lg flex items-center justify-between min-w-[300px] max-w-md`;
            flashMessage.style.opacity = '0';
            flashMessage.style.transform = 'translateX(100%)';
            flashMessage.style.transition = 'all 0.3s ease-out';
            flashMessage.innerHTML = `
                <div class="flex items-center">
                    <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'} mr-2"></i>
                    <span>${message}</span>
                </div>
                <button type="button" class="ml-4 text-white hover:text-gray-200 focus:outline-none" onclick="this.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            flashContainer.appendChild(flashMessage);
            
            // 显示消息
            setTimeout(() => {
                flashMessage.style.opacity = '1';
                flashMessage.style.transform = 'translateX(0)';
            }, 50);
            
            // 5秒后自动隐藏
            setTimeout(() => {
                flashMessage.style.opacity = '0';
                flashMessage.style.transform = 'translateX(100%)';
                
                // 完全移除元素
                setTimeout(() => {
                    flashMessage.remove();
                }, 300);
            }, 5000);
        }
        
        // 表格行悬停交互增强
        const projectTableRows = document.querySelectorAll('.project-table tbody tr');
        projectTableRows.forEach(row => {
            // 跳过空状态行
            if (row.querySelector('.empty-state')) return;
            
            row.addEventListener('mouseenter', function() {
                this.style.transform = 'scale(1.002)';
                this.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)';
                this.style.transition = 'all 0.2s ease';
            });
            
            row.addEventListener('mouseleave', function() {
                this.style.transform = '';
                this.style.boxShadow = '';
            });
        });
        
        // 进度条动画增强
        const progressBarElements = document.querySelectorAll('.progress-bar');
        setTimeout(() => {
            progressBarElements.forEach(bar => {
                const width = bar.style.width;
                bar.style.width = '0%';
                bar.style.transition = 'width 1s ease-in-out';
                setTimeout(() => {
                    bar.style.width = width;
                }, 100);
            });
        }, 300);
        
        // 项目立项弹窗功能
        const projectInitiationBtn = document.getElementById('project-initiation-btn');
        const projectInitiationModal = document.getElementById('project-initiation-modal');
        const closeInitiationModal = document.getElementById('close-initiation-modal');
        const cancelInitiation = document.getElementById('cancel-initiation');
        const projectInitiationForm = document.getElementById('project-initiation-form');
        
        // 显示项目立项弹窗
        if (projectInitiationBtn) {
            projectInitiationBtn.addEventListener('click', function() {
                projectInitiationModal.classList.remove('hidden');
            });
        }
        
        // 关闭项目立项弹窗
        function closeProjectInitiationModal() {
            projectInitiationModal.classList.add('hidden');
            // 重置表单
            if (projectInitiationForm) {
                projectInitiationForm.reset();
            }
        }
        
        // 点击关闭按钮关闭弹窗
        if (closeInitiationModal) {
            closeInitiationModal.addEventListener('click', closeProjectInitiationModal);
        }
        
        // 点击取消按钮关闭弹窗
        if (cancelInitiation) {
            cancelInitiation.addEventListener('click', closeProjectInitiationModal);
        }
        
        // 点击弹窗外部区域关闭弹窗
        projectInitiationModal.addEventListener('click', function(e) {
            if (e.target === projectInitiationModal) {
                closeProjectInitiationModal();
            }
        });
        
        // 处理表单提交
        if (projectInitiationForm) {
            projectInitiationForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // 使用AJAX提交表单
                const formData = new FormData(this);
                const action = this.getAttribute('action');
                
                fetch(action, {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (response.redirected) {
                        // 如果服务器返回重定向，则重定向页面
                        window.location.href = response.url;
                        return;
                    }
                    return response.json().then(data => {
                        if (!response.ok) {
                            throw new Error(data.message || '提交失败');
                        }
                        return data;
                    });
                })
                .then(data => {
                    if (data && data.success) {
                        // 显示成功消息
                        showNotification('项目立项成功！', 'success');
                        // 关闭弹窗
                        closeProjectInitiationModal();
                        // 重定向到项目详情页
                        setTimeout(() => {
                            window.location.href = `/projects/${data.project_id}`;
                        }, 1500);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showNotification('项目立项失败：' + error.message, 'error');
                });
            });
        }
    });
</script>
{% endblock %}